<template>
  <el-dialog :title="options.title" :visible.sync="options.dialogVisible" width="80%" top="5vh" @close="handleClose">
    <div class="preview-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-wrapper">
        <i class="el-icon-loading"></i>
        加载中...
      </div>

      <!-- 图片预览 -->
      <img v-if="fileType === 'image'" :src="options.url" class="preview-content" alt="图片预览" @error="handleError" />

      <embed v-if="fileType === 'pdf'" class="preview-content text-preview " :src="options.url" type="application/pdf"
        width="100%" height="500px" />

      <!-- 文本预览 -->
      <pre v-if="fileType === 'text'" class="preview-content text-preview">{{ textContent }}</pre>

      <!-- Office 文档预览 -->


      <div v-if="isOfficeFile" class="docx-viewer-container preview-content text-preview docx-content">
        <!-- 文档预览区域 -->
        <vue-office-docx style="width:100%;height:100%" :src="options.url" ref="docxViewer" @rendered="handleRendered"
          @error="handleError" />

        <!-- 操作工具栏 -->

      </div>

      <!-- 下载提示 -->
      <div class="unsupported-type">
        <el-button type="primary" @click="handleDownload">
          <i class="el-icon-download"></i>
          下载文件
        </el-button>

        <el-button v-if="isOfficeFile" type="primary">
          <i class="el-icon-printer"></i>
          打印文档
        </el-button>

        <el-button v-if="isOfficeFile" @click="downloadPdf">
          <i class="el-icon-document"></i>
          导出PDF
        </el-button>


      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="options.dialogVisible = false">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch, Ref } from 'vue-property-decorator';
import VueOfficeDocx from '@vue-office/docx'

@Component({
  components: { VueOfficeDocx }
})
export default class FileViewDialog extends Vue {
  @Prop({ required: true }) options!: any;
  @Ref("docxViewer") docxViewer;
  loading = true;
  textContent = '';
  printContent: any;
  supportedTypes = [
    'pdf', 'png', 'jpg', 'jpeg', 'gif', // 图片和PDF
    'txt', 'log', 'json', 'xml', 'csv', // 文本类型
    'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx' // Office文档
  ];


  get fileType() {
    if (!this.options.url) return '';
    const ext = this.options.type;

    if (['png', 'jpg', 'jpeg', 'gif'].includes(ext)) return 'image';
    if (ext === 'pdf') return 'pdf';
    if (['txt', 'log', 'json', 'xml', 'csv'].includes(ext)) return 'text';
    return ext;
  }

  get isOfficeFile() {
    const officeTypes = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];

    return officeTypes.includes(this.fileType);
  }

  @Watch('options.url', { immediate: true })
  async onUrlChange() {

    if (!this.options.url) return;

    this.loading = true;
    try {
      if (this.fileType === 'text') {
        this.loadTextFile('utf-8');
      }

    } catch (error) {
      // this.handleError(error);
    } finally {
      this.loading = false;
    }
  }

  // 获取渲染后的HTML内容
  handleRender() {
    this.printContent = this.docxViewer.$el.innerHTML
  }

  handleRendered() {
    console.log('DOCX渲染完成');
  }

  async loadTextFile(encoding = 'utf-8') {
    try {

      const response = await fetch(this.options.url);
      const buffer = await response.arrayBuffer();

      const decoder = new TextDecoder(encoding);
      this.textContent = decoder.decode(buffer);
    } catch (error) {
      // 尝试其他编码
      if (encoding === 'utf-8') {
        await this.loadTextFile('gbk');
      } else {
        this.textContent = '解码失败';
      }
    }
  }

  handleDownload() {
    const link = document.createElement('a');
    link.href = this.options.url;
    link.setAttribute('download', '');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  downloadPdf() {
    const link = document.createElement('a');
    link.href = this.options.url.replace('file', 'downloadPdf');
    link.setAttribute('download', '');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  handleError(error: any) {
    console.error('预览失败:', error);
    this.$message.error('文件加载失败，请尝试下载查看');
    this.options.dialogVisible = false;
  }

  handleClose() {
    this.textContent = '';
    this.loading = false;
  }
}
</script>

<style scoped>
.preview-container {
  position: relative;
  height: 70vh;
  min-height: 400px;
}

.loading-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #666;
}

.preview-content {
  width: 100%;
  height: 100%;
  border: none;
  margin-right: 10px;
}

.text-preview {
  white-space: pre-wrap;
  padding: 0px;
  font-family: monospace;
  overflow: auto;
  background: #f8f8f8;
  border-radius: 4px;
}

.office-iframe {
  min-height: 600px;
}

.unsupported-type {
  text-align: center;
  padding: 40px 0;
}

.unsupported-type p {
  margin-bottom: 20px;
  color: #666;
}
</style>